#include <memory>
#include <fstream>
#include "HttpServer.hpp"
#include "Util.hpp"

#define ROOT "./wwwroot"      // web根目录
#define HOMEPAGE "index.html" // 首页

using namespace std;

uint16_t server_port = 0;

void HandleHttpRequest(int sock)
{
    char buffer[1024];
    while (true)
    {
        // 1.获取HTTP请求
        ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0);
        if (s > 0)
        {
            buffer[s] = 0;
            cout << "----------------" << endl;
            cout << buffer << endl;
            cout << "----------------" << endl;
        }
        else if (s == 0)
        {
        }

        // // 2.构建HTTP响应
        vector<string> vline;
        Util::CutString(buffer, "\r\n", &vline); // 截取所有行

        vector<string> vblock;
        Util::CutString(vline[0], " ", &vblock); // 截取请求行的所有字段

        // vblock[0]:方法
        // vblock[1]:请求资源路径
        string target = vblock[1];
        // cout << "target" << target << endl;
        if (target == "/")
            target += string(HOMEPAGE);
        target = string(ROOT) + target;

        string content;
        ifstream in(target); // 打开资源文件
        // cout << "target" << target << endl;
        if (in.is_open())
        {
            string line;
            while (getline(in, line)) // 读取
            {
                content += line;
            }
        }
        else
        {
        } // 打开失败
        in.close();

        // 网络发送
        string HTTPResponse;
        if (content.empty())
        {
            // HTTPResponse = "HTTP/1.1 404 NotFound\r\n";
            HTTPResponse = "HTTP/1.1 302 Found\r\n";
            HTTPResponse += "Location: http://82.157.96.181:" + to_string(server_port) + "/404.html\r\n";
        }
        else
            HTTPResponse = "HTTP/1.1 200 ok\r\n";
        // HTTPResponse += "Content-Length:" + to_string(content.size()) + "\r\n";
        // HTTPResponse += "Content-Type:text/html\r\n";
        HTTPResponse += "Cookie:这是一个cookie\r\n";
        HTTPResponse += "\r\n";
        HTTPResponse += content;
        send(sock, HTTPResponse.c_str(), HTTPResponse.size(), 0);
        // cout << "----------------------------------" << endl;
        cout << content.size() << endl;
        // cout << "----------------------------------" << endl;
    }
}

void Usage(const char *proc)
{
    cout << "Usage: " << proc << " port" << endl;
}

// ./server ip port 启动Http服务器
int main(int argc, const char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    uint16_t port = atoi(argv[1]); // 获取命令行输入的port
    server_port = port;
    unique_ptr<HttpServer> httpServer(new HttpServer(port));
    httpServer->BindService(HandleHttpRequest);
    httpServer->Start();

    return 0;
}